package com.example.test_app;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.example.myhttp.CallBackObject;
import com.example.myhttp.GsonInterface;
import com.example.myhttp.Ihttp;
import com.example.myhttp.OkHttpInterface;
import com.example.test_app.bean.ChickenSoup;
import com.google.gson.Gson;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Implementation of App Widget functionality.
 */
public class NewAppWidget extends AppWidgetProvider {
    public static final String url_ChickenSoup = "https://api.btstu.cn/yan/api.php?charset=utf-8&encode=json";
    public static String title = "标题";
    public static String content = "没有数据哦";
    public static final String REFRESH_WIDGET = "com.ohuang.REFRESH_WIDGET";

    static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                                int appWidgetId) {
        Ihttp.getInstance().get(url_ChickenSoup, ChickenSoup.class, new CallBackObject<ChickenSoup>() {
            @Override
            public void fail(String s) {
                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

                content = s;
                title = sdf.format(new Date(System.currentTimeMillis()));
                RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);
                views.setTextViewText(R.id.tv_time, title);
                views.setTextViewText(R.id.tv_content, content);
                Intent btIntent = new Intent().setAction(REFRESH_WIDGET);
                btIntent.setComponent(new ComponentName("com.example.test_app",
                        "com.example.test_app.NewAppWidget"));
                PendingIntent btPendingIntent = PendingIntent.getBroadcast(context, 0, btIntent, 0);
                views.setOnClickPendingIntent(R.id.image_top, btPendingIntent);
                // Instruct the widget manager to update the widget
                appWidgetManager.updateAppWidget(appWidgetId, views);
            }

            @Override
            public void success(ChickenSoup ojb) {
                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
                content = ojb.getText();
                title = sdf.format(new Date(System.currentTimeMillis()));
                RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);
                views.setTextViewText(R.id.tv_time, title);
                views.setTextViewText(R.id.tv_content, content);
                Intent btIntent = new Intent().setAction(REFRESH_WIDGET);
                btIntent.setComponent(new ComponentName("com.example.test_app",
                        "com.example.test_app.NewAppWidget"));
                PendingIntent btPendingIntent = PendingIntent.getBroadcast(context, 0, btIntent, 0);
                views.setOnClickPendingIntent(R.id.image_top, btPendingIntent);

                appWidgetManager.updateAppWidget(appWidgetId, views);
            }
        });


    }

    private static void getData() {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient okHttpClient = new OkHttpClient();
                Request request = new Request.Builder().url(url_ChickenSoup).get().build();
                try {
                    Response response = okHttpClient.newCall(request).execute();
                    assert response.body() != null;
                    String json = response.body().string();
                    ChickenSoup c = new Gson().fromJson(json, ChickenSoup.class);

                    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

                    content = c.getText();
                    title = sdf.format(new Date(System.currentTimeMillis())); // 时间戳转换日期
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });
        thread.start();
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        // There may be multiple widgets active, so update all of them
        Log.d("TAG", "onUpdate: ");
        for (int appWidgetId : appWidgetIds) {
            updateAppWidget(context, appWidgetManager, appWidgetId);
        }
    }

    @Override
    public void onEnabled(Context context) {
        // Enter relevant functionality for when the first widget is created
    }

    @Override
    public void onDisabled(Context context) {
        // Enter relevant functionality for when the last widget is disabled
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);

        if (action.equals("com.ohuang.REFRESH_WIDGET")) {
            getData();
            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);
            views.setTextViewText(R.id.tv_time, title);
            views.setTextViewText(R.id.tv_content, content);

            // Instruct the widget manager to update the widget
            ComponentName componentName = new ComponentName(context, NewAppWidget.class);
            appWidgetManager.updateAppWidget(componentName, views);
            return;
        }
        super.onReceive(context, intent);

    }
}